<?php
declare(strict_types=1);

namespace Kiri\Router\Validator;

use Kiri;
use Kiri\Router\Base\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

/**
 *
 */
class ValidatorMiddleware implements MiddlewareInterface
{


	/**
	 * @param ResponseInterface $response
	 * @param string            $class
	 * @param string            $method
	 */
    public function __construct(public ResponseInterface $response ,public string $class, public string $method)
    {
    }


    /**
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     * @throws
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $validator = Middleware::getValidator($this->class, $this->method);
        if (!$validator->run($request)) {
            Kiri::getLogger()->println($request->getUri()->getPath() . ' `' . $validator->error() . '`');

            return $this->response->html($validator->error(), 415);
        } else {
            return $handler->handle($request);
        }
    }
}
